package org.ricks.log;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author chenwei
 * @Description:
 * @date 2023/1/918:15
 */
public class LogPath {

    /**
     * 配置存档路径
     */
    private String path = "log";
    private final boolean activate;
    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    private String prefix = "/log-";
    private String suffix = "";

    LogPath(String path) {
        this.path = path;
        this.activate = path != null && !"".equals(path);

        if (activate) {
            int start = path.indexOf("{");
            int end = path.lastIndexOf("}");

            // 有配置日期格式后缀
            if (start > 0 && end > start) {
                String dateFormat = path.substring(start + 1, end);
                this.formatter = DateTimeFormatter.ofPattern(dateFormat);

                this.prefix = path.substring(0, start);
                this.suffix = path.substring(end + 1);
            }
        }
    }

    public String getPath() {
        return path;
    }

    /**
     * 日志存储文件功能是否激活.
     *
     * @return 日志存储文件功能是否激活
     */
    public boolean isActivate() {
        return activate;
    }

    /**
     * 计算当前日志时间所对应的文件路径.
     *
     * @param date 日志时间
     * @return 日志文件路径
     */
    public String getPath(LocalDateTime date) {
        if (formatter == null) {
            return path;
        }
        return new StringBuilder(path).append(prefix).append(date.format(formatter)).append(suffix).toString();
    }
}
